<?php

namespace app\admin\logic;

use app\admin\model\Company;
use app\admin\model\Goods;
use app\admin\model\GoodsSpec;
use app\common\model\SystemRegion;
use app\common\exception\ApiException;
use support\Cache;
use think\facade\Db;

/**
 * 部门逻辑层
 */
class CompanyLogic extends BaseLogic
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new Company();
    }
    
    /**
     * 添加数据
     * @param $data
     * @return mixed
     */
    public function add($data): mixed
    {
        $params = $this->handleData($data);
        $id = 0;
        $this->model->transaction(function () use ($params, &$id) {
            $companyData = $params['company_data'] ?? [];
            $accountData = $params['account_data'] ?? [];
            
            $this->model->save($companyData);
            $id = $this->model->id;
            $accountData['company_id'] = $id;
            $this->model->user()->save($accountData);
        });
        return $id;
    }
    
    /**
     * 读取数据
     * @param $id
     * @return mixed
     */
    public function read($id): mixed
    {
        $model = $this->model->field('*, "" as area')->with(['business', 'project', 'operation'])->findOrEmpty($id);
        if ($model->isEmpty()) {
            throw new ApiException('数据不存在');
        }
        return $model;
    }
    
    /**
     * 修改数据
     * @param $id
     * @param $data
     * @return mixed
     */
    public function edit($id, $data): mixed
    {
        $model = $this->model->findOrEmpty($id);
        if ($model->isEmpty()) {
            throw new ApiException('数据不存在');
        }
        $params = $this->handleData($data);
        $companyData = $params['company_data'] ?? [];
        $accountData = $params['account_data'] ?? [];
        $userInfo = $cacheKey = null;

        if (!empty($accountData)) {
            $userInfo = $model->user()->where([
                'company_id' => $id,
                'is_super' => 1,
                'username' => $accountData['username'],
            ])->findOrEmpty();
            if ($userInfo->isEmpty()) {
                throw new ApiException('未找到相关账号信息');
            }
            $cacheKey = 'company_edit_count:' . $userInfo->id . ':' . date('Ymd');
            $count = Cache::get($cacheKey, 0);
            if ($count >= 3) {
                throw new ApiException('今日修改次数已达上限，请明日再试');
            }
        }

        $this->model->transaction(function () use ($model, $companyData, $accountData, $userInfo, $cacheKey) {
            $warehouseRate = $companyData['warehouse_rate'] ?? $model->warehouse_rate;
            $warehousingDistributionRate = $companyData['warehousing_distribution_rate'] ?? $model->warehousing_distribution_rate;
            GoodsSpec::alias('gs')->leftJoin(Goods::getTable() .' g','gs.goods_id = g.id')->where('g.company_id', $model->id)->update([
                'operation_warehouse_delivery_fee' => Db::raw("agree_price * {$warehousingDistributionRate} / 100"),
                'operation_centralized_warehouse_fee' => Db::raw("agree_price * {$warehouseRate} / 100")
            ]);
            $model->save($companyData);
            if (!empty($accountData)) {
                unset($accountData['username']);
                $userInfo->save($accountData);
                Cache::set($cacheKey, Cache::get($cacheKey, 0) + 1);
            }
        });
        return $model->save($data);
    }
    
    /**
     * 删除数据
     * @param $id
     * @return mixed
     */
    public function destroy($ids): mixed
    {
        $this->model->transaction(function () use ($ids) {
            $this->model->destroy($ids);
            $this->model->user()->whereIn('company_id', $ids)->delete();
        });
        return true;
    }
    
    private function handleData($data): array
    {
        if (!empty($data['cooperation_start_time'])) {
            $data['cooperation_start_time'] = date('Y-m-d', strtotime($data['cooperation_start_time']));
        }
        if (!empty($data['cooperation_end_time'])) {
            $data['cooperation_end_time'] = date('Y-m-d', strtotime($data['cooperation_end_time']));
        }
        if (!empty($data['area_id'])) {
            $data['city_id'] = SystemRegion::where('id', $data['area_id'])->value('parent_id');
            if (!empty($data['city_id'])) {
                $data['province_id'] = SystemRegion::where('id', $data['city_id'])->value('parent_id');
            }
        }
        
        if (empty($data['id'])) {
            $accountData = [
                'username' => $data['account'] ?? '',
                'company_id' => $data['id'] ?? 0,
                'head_img' => $data['avatar'] ?? '',
            ];
            $data['create_time'] = time();
            $data['status'] = $data['status'] ?? 1;
            $accountData = array_merge($accountData, [
                'password' => company_password_hash(empty($data['password']) ? config('common.default_password') : $data['password']),
                'is_super' => 1
            ]);
        }
        
        unset($data['account'], $data['password'], $data['avatar']);
        return [
            'company_data' => $data,
            'account_data' => $accountData ?? [],
        ];
    }

}
